package com.sibu.yx.promotion.common.enums;

import java.time.Duration;
import java.util.Objects;

public enum RedisKeyEnum implements RedisKey {
    /**
     * get("a")获取结果为：BASE_PRE_KEY:demo:a:suffix
     * get()获取结果为：BASE_PRE_KEY:demo:suffix
     * 存活时间：7天
     */
    DEMO("demo", "suffix", Duration.ofDays(7).getSeconds()),

    /**
     * 短信验证码
     * 短信验证码存活时间为30分钟
     */
    REDIS_SMS_TEXT("sms", "code", Duration.ofMinutes(30).getSeconds()),

    /**
     * 城市排行榜数据版本号
     * 存活时间：90天
     */
    REDIS_CITY_RANK_DATA_VERSION("city_rank_data_version", null, Duration.ofDays(90).getSeconds()),

    REDIS_CITY_OPERATION_LOCK("city_operation_lock", null, Duration.ofSeconds(10).getSeconds()),
    ;

    /**
     * 前缀key(不带冒号)
     */
    private String preKey;

    /**
     * 后缀key(不带冒号)
     */
    private String sufKey;


    /**
     * 存活时间，-1：永久
     */
    private long liveSeconds;

    RedisKeyEnum(String preKey) {
        this(preKey, "", NEVER_EXPIRED);
    }

    RedisKeyEnum(String preKey, String sufKey) {
        this(preKey, sufKey, NEVER_EXPIRED);
    }

    RedisKeyEnum(String preKey, String sufKey, long liveSeconds) {
        this.preKey = preKey;
        this.sufKey = sufKey;
        this.liveSeconds = liveSeconds;
    }

    /**
     * value = basePreKey + : + preKey + : + value + : + sufKey;
     *
     * @param value
     * @return
     */
    @Override
    public String get(Object value) {
        Objects.requireNonNull(value);
        StringBuilder strBu = new StringBuilder(60).
                append(BASE_PRE_KEY).append(preKey).append(KEY_SPLIT).append(value.toString());
        if (sufKey != null && !sufKey.isEmpty()) {
            strBu.append(KEY_SPLIT).append(sufKey);
        }
        return strBu.toString();
    }

    @Override
    public String getNoBase(Object value) {
        Objects.requireNonNull(value);
        StringBuilder strBu = new StringBuilder(60).append(preKey).append(KEY_SPLIT).append(value.toString());
        if (sufKey != null && !sufKey.isEmpty()) {
            strBu.append(KEY_SPLIT).append(sufKey);
        }
        return strBu.toString();
    }

    /**
     * value = basePreKey + : + preKey  + : + sufKey
     *
     * @return
     */
    public String get() {
        StringBuilder strBu = new StringBuilder(60).
                append(BASE_PRE_KEY).append(KEY_SPLIT)
                .append(preKey);
        if (sufKey != null && !sufKey.isEmpty()) {
            strBu.append(KEY_SPLIT).append(sufKey);
        }
        return strBu.toString();
    }

    @Override
    public boolean hasSetExpire() {
        return liveSeconds != NEVER_EXPIRED;
    }

    @Override
    public long getLiveSecond() {
        return liveSeconds;
    }

    @Override
    public String getField() {
        return sufKey;
    }

    @Override
    public String getPreKey() {
        return preKey;
    }
}
